"use client";

import { useState, useEffect } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { useToast } from '@/hooks/use-toast';

export default function AccountPage() {
  const { data: session, status, update } = useSession();
  const router = useRouter();
  const { toast } = useToast();
  const [isLoading, setIsLoading] = useState(false);
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    password: '',
    newPassword: '',
  });
  const [editEmail, setEditEmail] = useState(false);
  const [editPassword, setEditPassword] = useState(false);

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.push('/sign-in');
    }
    if (session?.user) {
      setFormData((prev) => ({
        ...prev,
        name: session.user.name || '',
        email: session.user.email || '',
      }));
    }
  }, [session, status, router]);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  // 邮箱修改API
  const handleEmailUpdate = async (e) => {
    e.preventDefault();
    setIsLoading(true);
    try {
      const res = await fetch('/api/user/update-email', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ newEmail: formData.email }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || '邮箱更新失败');
      toast({ description: '邮箱已更新', duration: 2000 });
      setEditEmail(false);
      // 刷新session
      update();
    } catch (err) {
      toast({ variant: 'destructive', description: err.message, duration: 2000 });
    } finally {
      setIsLoading(false);
    }
  };

  // 密码修改API
  const handlePasswordUpdate = async (e) => {
    e.preventDefault();
    setIsLoading(true);
    try {
      const res = await fetch('/api/user/update-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ oldPassword: formData.password, newPassword: formData.newPassword }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || '密码更新失败');
      toast({ description: '密码已更新', duration: 2000 });
      setEditPassword(false);
      setFormData((prev) => ({ ...prev, password: '', newPassword: '' }));
    } catch (err) {
      toast({ variant: 'destructive', description: err.message, duration: 2000 });
    } finally {
      setIsLoading(false);
    }
  };

  if (status === 'loading') {
    return <div className="p-8 text-center">加载中...</div>;
  }
  if (!session) {
    return null;
  }

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="max-w-2xl mx-auto">
        <Card>
          <CardHeader>
            <CardTitle>账户信息</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex flex-col items-center mb-8">
              <Avatar className="h-20 w-20 mb-2">
                <AvatarImage src="" alt={formData.name} />
                <AvatarFallback>{formData.name?.charAt(0)}</AvatarFallback>
              </Avatar>
              <div className="text-lg font-semibold">{formData.name}</div>
            </div>
            <div className="space-y-6">
              {/* 用户名展示 */}
              <div>
                <Label>用户名</Label>
                <Input value={formData.name} readOnly className="mt-1 bg-gray-100" />
              </div>
              {/* 邮箱展示与修改 */}
              <div>
                <Label>电子邮件</Label>
                {!editEmail ? (
                  <div className="flex items-center gap-2 mt-1">
                    <Input value={formData.email} readOnly className="bg-gray-100" />
                    <Button size="sm" variant="outline" onClick={() => setEditEmail(true)}>修改</Button>
                  </div>
                ) : (
                  <form onSubmit={handleEmailUpdate} className="flex items-center gap-2 mt-1">
                    <Input
                      name="email"
                      type="email"
                      value={formData.email}
                      onChange={handleChange}
                      required
                    />
                    <Button size="sm" type="submit" disabled={isLoading}>
                      {isLoading ? '保存中...' : '保存'}
                    </Button>
                    <Button size="sm" variant="ghost" type="button" onClick={() => setEditEmail(false)}>
                      取消
                    </Button>
                  </form>
                )}
              </div>
              {/* 密码修改 */}
              <div>
                <Label>用户密码</Label>
                {!editPassword ? (
                  <div className="flex items-center gap-2 mt-1">
                    <Input value="********" readOnly className="bg-gray-100" type="password" />
                    <Button size="sm" variant="outline" onClick={() => setEditPassword(true)}>修改</Button>
                  </div>
                ) : (
                  <form onSubmit={handlePasswordUpdate} className="space-y-2 mt-1">
                    <Input
                      name="password"
                      type="password"
                      value={formData.password}
                      onChange={handleChange}
                      placeholder="当前密码"
                      required
                    />
                    <Input
                      name="newPassword"
                      type="password"
                      value={formData.newPassword}
                      onChange={handleChange}
                      placeholder="新密码"
                      required
                    />
                    <div className="flex gap-2 mt-1">
                      <Button size="sm" type="submit" disabled={isLoading}>
                        {isLoading ? '保存中...' : '保存'}
                      </Button>
                      <Button size="sm" variant="ghost" type="button" onClick={() => setEditPassword(false)}>
                        取消
                      </Button>
                    </div>
                  </form>
                )}
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
} 